package com.example.administrator.printoutindemo.mvp.ui.activity;

import android.annotation.SuppressLint;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.dds.soap.SoapListener;
import com.dds.soap.SoapParams;
import com.dds.soap.SoapUtil;
import com.example.administrator.printoutindemo.R;
import com.example.administrator.printoutindemo.di.component.DaggerZhouBaoComponent;
import com.example.administrator.printoutindemo.di.module.ZhouBaoModule;
import com.example.administrator.printoutindemo.mvp.contract.ZhouBaoContract;
import com.example.administrator.printoutindemo.mvp.presenter.ZhouBaoPresenter;
import com.example.administrator.printoutindemo.mvp.ui.entity.ZhouBao;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.redking.view.fragment.DocOpenFragment;
import com.xiaoxing.gifloadingview.LoadingDialogUtil;

import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;

import butterknife.BindView;
import im.delight.android.webview.AdvancedWebView;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import okhttp3.ResponseBody;

import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.ACTIVITY_ZHOU_BAO)
public class ZhouBaoActivity extends BaseActivity<ZhouBaoPresenter> implements ZhouBaoContract.View, AdvancedWebView.Listener {
    @BindView(R.id.webview)
    AdvancedWebView webview;
    /**
     * 提交盘点结果
     *
     * @param user_id
     */
    String result;
    @BindView(R.id.empty)
    View mEmptyLayout;
    @BindView(R.id.empty_text)
    TextView empty_text;
    @BindView(R.id.empty_image)
    ImageView empty_image;

    @BindView(R.id.ll_doc_frag)
    RelativeLayout ll_doc_frag;
    FragmentManager fragmentManager;
    FragmentTransaction beginTransaction;
    DocOpenFragment docOpenFragment;
    String fileUrl = "http://dezhou.xywuhe.com/workReport/23175578-c55a-42ec-93ae-75324681c528.docx";
    //文件存储位置
    private String docPath = "/sdcard/zhoubao/";
    //文件名称
    private String docName = "test.doc";
    //html文件存储位置
    private String savePath = docPath;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    //进度条的值
                    int i = msg.arg1;
            }
            if (msg.arg1 == 100) {
//                displayFromFile(new File(Environment.getExternalStorageDirectory().getAbsolutePath(), result.substring(result.lastIndexOf("/") + 1)));

                docName = result.substring(result.lastIndexOf("/") + 1);
                String name = docName.substring(0, docName.indexOf("."));
                //convert2Html(docPath + docName, savePath + name + ".html");

                webview.setListener(ZhouBaoActivity.this, ZhouBaoActivity.this);
                webview.loadUrl("https://view.officeapps.live.com/op/view.aspx?src=http://dezhou.xywuhe.com/workReport/23175578-c55a-42ec-93ae-75324681c528.docx");
            }
        }
    };

    @Override
    protected void onDestroy() {
        webview.onDestroy();
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        webview.onActivityResult(requestCode, resultCode, intent);
    }

    @Override
    public void onBackPressed() {
        if (!webview.onBackPressed()) {
            return;
        }
        super.onBackPressed();
    }

    @SuppressLint("NewApi")
    @Override
    protected void onPause() {
        webview.onPause();
        super.onPause();
    }

    @SuppressLint("NewApi")
    @Override
    protected void onResume() {
        super.onResume();
        webview.onResume();
    }

    @Override
    public void onPageStarted(String url, Bitmap favicon) {

    }

    @Override
    public void onPageFinished(String url) {
        hideLoading();
    }

    @Override
    public void onPageError(int errorCode, String description, String failingUrl) {
    }

    @Override
    public void onDownloadRequested(String url, String suggestedFilename, String mimeType, long contentLength, String contentDisposition, String userAgent) {
    }

    @Override
    public void onExternalPageRequest(String url) {
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerZhouBaoComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .zhouBaoModule(new ZhouBaoModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_zhou_bao; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        ToolbarUtils.initToolbarTitleBack(this, getString(R.string.activity_zhou_bao));
//        getZhouBaoData();
        initEmpty();


        getLatestWorkReport(mSharedPreferencesHelper.getString(BaseConstants.UID));
    }

    private void initEmpty() {
        empty_image.setImageResource(com.xiaoxing.zhinenghuacangku.R.drawable.ic_empty);
        empty_text.setTextColor(Color.parseColor("#CFCFCF"));
        empty_text.setText("暂无数据");
    }

    private void getLatestWorkReport(String user_id) {

        showLoading();

        String methodName = "getLatestWorkReport";

        SoapUtil soapUtil = SoapUtil.getInstance(this);
        soapUtil.setDotNet(true);
        SoapParams params = new SoapParams();
        params.put("user_id", user_id);

        /**
         * 请求
         */
        soapUtil.callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                result = object.getProperty("getLatestWorkReportResult").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {

//                    mPresenter.downloadFileFromNet(result);
                    mEmptyLayout.setVisibility(View.GONE);
//                    webViewLoadData();
                    x5LoadData();

                } else {
                    hideLoading();
                    mEmptyLayout.setVisibility(View.VISIBLE);
                    webview.setVisibility(View.GONE);
                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());


    }

    @Override
    public void showLoading() {
        LoadingDialogUtil.showGifdialog2(getSupportFragmentManager(), R.drawable.public_loading);
    }

    @Override
    public void hideLoading() {
        LoadingDialogUtil.dismissDialog();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    private void webViewLoadData() {
        webview.setVisibility(View.VISIBLE);
        webview.setListener(ZhouBaoActivity.this, ZhouBaoActivity.this);
        webview.loadUrl("https://view.officeapps.live.com/op/view.aspx?src=" + result);
    }

    private void x5LoadData() {
        hideLoading();

        fragmentManager = getFragmentManager();
        beginTransaction = fragmentManager.beginTransaction();
        docOpenFragment = new DocOpenFragment();
        //设置文件路径
        docOpenFragment.setFilePath(result);

        beginTransaction.add(R.id.ll_doc_frag, docOpenFragment);
        beginTransaction.commit();
    }

    /**
     * 将html文件保存到sd卡
     */
    public void writeFile(String content, String path) {
        FileOutputStream fos = null;
        BufferedWriter bw = null;
        try {
            File file = new File(path);
            if (!file.exists()) {
                file.createNewFile();
            }
            fos = new FileOutputStream(file);
            bw = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"));
            bw.write(content);
        } catch (FileNotFoundException fnfe) {
            fnfe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            try {
                if (bw != null)
                    bw.close();
                if (fos != null)
                    fos.close();
            } catch (IOException ie) {
            }
        }
    }

    private void getZhouBaoData() {
        mPresenter.getZhouBaoData();
    }

    @Override
    public void getZhouBaoDataSuccess(ZhouBao entityData) {


    }

    @Override
    public void downloadFileFromNetSuccess(ResponseBody responseBody) {
        InputStream is = null;
        byte[] buf = new byte[2048];
        int len = 0;
        FileOutputStream fos = null;
        try {
            is = responseBody.byteStream();
            long total = responseBody.contentLength();
//            File file = new File(docPath + "/0/", result.substring(result.lastIndexOf("/") + 1));
            File file = makeFilePath(docPath, result.substring(result.lastIndexOf("/") + 1));
            fos = new FileOutputStream(file);
            long sum = 0;
            while ((len = is.read(buf)) != -1) {
                fos.write(buf, 0, len);
                sum += len;
                int progress = (int) (sum * 1.0f / total * 100);
                Log.d("h_bl", "progress=" + progress);
                Message msg = handler.obtainMessage();
                msg.what = 1;
                msg.arg1 = progress;
                handler.sendMessage(msg);
            }
            fos.flush();
        } catch (Exception e) {
        } finally {
            try {
                if (is != null)
                    is.close();
            } catch (IOException e) {
            }
            try {
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
            }
        }

    }

    // 生成文件
    public File makeFilePath(String filePath, String fileName) {
        File file = null;
        makeRootDirectory(filePath);
        try {
            file = new File(filePath + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    // 生成文件夹
    public static void makeRootDirectory(String filePath) {
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception e) {
            Log.i("error:", e + "");
        }
    }

    private void displayFromFile(File file) {

    }


}
